package updown.service.updown;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import updown.constant.MsgConstant;
import updown.data.ExecutorPoolUtil;
import updown.data.SseCacheData;
import updown.domain.TaskWrapper;
import updown.service.jar.UploadJarService;
import updown.util.SleepUtil;

/**
 * <p>Title: updown.service </p>
 * <p>Description:updown: - 回滚 service </p>
 *
 * @Author:jiangkaixin
 * @Date:2022/1/6
 * @Version: 1.0
 */
@Slf4j
@Service
public class RollbackService {
    @Autowired
    private UploadJarService uploadJarService;

    @Autowired
    private DownUpServiceWithRetry downUpServiceWithRetry;

    @Autowired
    private SseCacheData sseCacheData;

    /**
     * 回滚操作
     * @param taskWrapper
     */
    public void rollBack(TaskWrapper taskWrapper) {
        log.info("rollBack(),taskWrapper:{}",taskWrapper);
        // 1 根据传入的 file 地址，传送jar包到 对应的服务器
        if (!uploadJarService.sendJarToServerNew(taskWrapper)) {
            log.info("rollback 同步jar到servers 报错，停止停止回滚操作");
            sseCacheData.sendLastMsgAndThrowEx("同步到其他服务器节点有失败的，服务同步失败，请手动检查，服务器上的jar信息",taskWrapper);
        }
        log.info("rollBack() 发送jar 完成");
        // 2 上传完成之后，开始执行服务替换操作
        if(!downUpServiceWithRetry.executeDownUp(taskWrapper)){
            // 重启失败
            sseCacheData.sendLastMsgAndThrowEx("回滚服务，服务替换失败",taskWrapper);
        }
        // 3 服务重启成功
        sseCacheData.sendLastMsgAndComplete(MsgConstant.rollback_finish + taskWrapper.spendTime() + " 秒", taskWrapper);
        log.info("回滚 服务重启完成");
    }

    /**
     * 丢入线程池
     * @param taskWrapper
     */
    public void rollBackInPool(TaskWrapper taskWrapper) {
        ExecutorPoolUtil.executor.execute(()->{
            SleepUtil.sleepSeconds(1);
            rollBack(taskWrapper);
        });
    }
}
